﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.IO;

namespace WxTest.Controllers
{
    public class HomeController : Controller
    {
        const string Token = "token888666777111";  

        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

        public string Validate()
        {
            var ret = "hello wx!";
            var echoStr = Request.QueryString["echoStr"];

            if (CheckSignature())
            {
                if (!string.IsNullOrEmpty(echoStr))
                {
                    ret = echoStr;

                    //Response.Write(echoStr);
                    //Response.End();
                }
            }

            return ret;
        }

        /// <summary>  
        /// 验证微信签名  
        /// </summary>  
        /// * 将token、timestamp、nonce三个参数进行字典序排序  
        /// * 将三个参数字符串拼接成一个字符串进行sha1加密  
        /// * 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信。  
        /// <returns></returns>  
        private bool CheckSignature()
        {
            string signature = Request.QueryString["signature"];
            string timestamp = Request.QueryString["timestamp"];
            string nonce = Request.QueryString["nonce"];

            var sw = new StreamWriter(Server.MapPath("/") + "log.txt", true);
            sw.WriteLine("signature: {0}", signature);
            sw.WriteLine("timestamp: {0}", timestamp);
            sw.WriteLine("nonce: {0}", nonce);
            sw.Flush();
            sw.Close();
            sw.Dispose();

            string[] ArrTmp = { Token, timestamp, nonce };
            Array.Sort(ArrTmp);     //字典排序  
            string tmpStr = string.Join("", ArrTmp);
            tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
            tmpStr = tmpStr.ToLower();
            if (tmpStr == signature)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
